#ifndef TCPSERVER_HPP
#define TCPSERVER_HPP

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <unistd.h>
#include "Log.hpp"

#define BACKLOG 5

class TcpServer
{
private:
    int _port;
    int _listen_sock;
    static TcpServer *svr;
private:
    TcpServer(int port) : _port(port), _listen_sock(-1) {}  
    TcpServer(const TcpServer &s) = delete;  // 删除拷贝构造函数，防止复制
    TcpServer &operator=(const TcpServer &s) = delete;  // 删除赋值运算符，防止复制
public:
    static TcpServer *GetInstance(int port)
    {
        if (svr == nullptr)
        {
            static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
            pthread_mutex_lock(&_mutex);
            if (svr == nullptr)
            {
                svr = new TcpServer(port);
                svr->InitServer();
            }
            pthread_mutex_unlock(&_mutex);
        }
        return svr;
    }
    void InitServer()
    {
        Socket();
        Bind();
        Listen();
        LOG(INFO, "TcpServer Init success!");
    }

    void Socket()
    {
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sock < 0)
        {
            LOG(FATAL, "socket error!");
            exit(1);
        }
        int opt = 1;
        setsockopt(_listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        LOG(INFO, "socket create success!");
    }

    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // 云服务器不能直接绑定公网IP

        if (bind(_listen_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error!");
            exit(2);
        }
        LOG(INFO, "bind success!");
    }

    void Listen()
    {
        if (listen(_listen_sock, BACKLOG) < 0)
        {
            LOG(FATAL, "listen error!");
            exit(3);
        }
        LOG(INFO, "listen success!");
    }

    int GetListenSock()
    {
        return _listen_sock;
    }

    ~TcpServer()
    {
        if(_listen_sock >= 0)
        {
            close(_listen_sock);
        }
    }
};
TcpServer *TcpServer::svr = nullptr;

#endif